import { Card, Button, Table, Modal, Form, Input, Upload, message, Popconfirm } from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/lib/table";
import { useEffect, useState } from "react";
import "./trademark.less";
import type { TrademarkData } from "@/api/trademark";
import trademarkApi from "@/api/trademark";
import { RcFile, UploadChangeParam, UploadFile, UploadProps } from "antd/lib/upload/interface";

function TrademarkPage() {
  // 打开添加品牌遮罩
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [rowId, setRowId] = useState<number>(-1);

  // 获取 form 对象
  const [form] = Form.useForm();

  // 分页数据
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(10);

  // 品牌数据
  const [trademarkList, setTrademarkList] = useState<TrademarkData[]>([]);

  const columns: ColumnsType<any> = [
    {
      title: "序号",
      align: "center",
      width: 120,
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      align: "center",
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      // dataIndex: "logoUrl",
      align: "center",
      render: row => <img className="trademarkLogo" src={row.logoUrl} alt={row.tmName} />,
    },
    {
      title: "操作",
      width: 250,
      render: row => {
        return (
          <>
            <Button
              icon={<EditOutlined />}
              className="upData"
              type="primary"
              onClick={updateTrademark(row)}
            >
              修改
            </Button>
            <Popconfirm
              title={`确定要删除${row.tmName}吗?`}
              onConfirm={confirm(row.id)}
              onCancel={cancel}
              okText="Yes"
              cancelText="No"
            >
              <Button icon={<DeleteOutlined />} type="primary" className="delete">
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  // 获取品牌列表信息
  const getTrademark = async (page = current, limit = pageSize) => {
    const result = await trademarkApi.getTrademarkList(page, limit);
    setTrademarkList(result.records);
    setTotal(result.total);
  };

  // 添加和修改品牌
  const addTrademark = async (fieldsValue: TrademarkData) => {
    await trademarkApi.addOrUpdate(fieldsValue);
  };

  // 删除品牌
  const deleteTrademark = async (id: number) => {
    await trademarkApi.remove(id);
  };

  // 修改数据
  const updateTrademark = (row: TrademarkData) => {
    return () => {
      console.log(row);
      setTimeout(() => {
        form.setFieldsValue({
          id: row.id,
          tmName: row.tmName,
          logoUrl: row.logoUrl,
        });
      }, 100);

      setRowId(row.id as number);
      setImageUrl(row.logoUrl);
      showModal();
    };
  };

  // 发送请求
  useEffect(() => {
    getTrademark();
  }, [current, pageSize]);

  // 添加按钮
  const openModal = () => {
    setRowId(-1);
    setImageUrl("");
    showModal();
  };
  const showModal = () => {
    if (rowId === -1) {
      form.resetFields();
    }
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  // 转化图片
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const handleChange: UploadProps["onChange"] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, url => {
        setLoading(false);
        setImageUrl(info.file.response.data);
      });
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />} <div style={{ marginTop: 8 }}>Upload</div>{" "}
    </div>
  );

  // 收集数据
  const onFinish = async () => {
    let fieldsValue = await form.validateFields();
    console.log(fieldsValue);
    console.log(rowId);
    console.log(imageUrl);
    if (rowId === -1) {
      let obj1 = {
        tmName: fieldsValue.tmName,
        logoUrl: imageUrl as string,
      };
      addTrademark(obj1);
    } else {
      let obj = {
        id: rowId,
        tmName: fieldsValue.tmName,
        logoUrl: imageUrl as string,
      };
      addTrademark(obj);
    }
    getTrademark();
    setIsModalOpen(false);
    form.resetFields();
  };

  // 删除品牌
  const confirm = (id: number) => {
    return () => {
      console.log(id);
      deleteTrademark(id);
      getTrademark();
    };
  };

  const cancel = () => {
    message.error("删除取消");
  };

  return (
    <Card>
      <Card>
        <Button type="primary" icon={<PlusOutlined />} onClick={openModal}>
          添加
        </Button>

        <Modal title="添加品牌" open={isModalOpen} footer={[]} onCancel={handleCancel}>
          <Form form={form} onFinish={onFinish}>
            <Form.Item
              label="品牌名称"
              name="tmName"
              rules={[{ required: true, message: "请输入品牌名称" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="品牌LOGO"
              name="logoUrl"
              valuePropName="logoUrl"
              rules={[{ required: true, message: "请选择要上传的图片" }]}
            >
              <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                           {" "}
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%", height: "90%" }} />
                ) : (
                  uploadButton
                )}
                         {" "}
              </Upload>
            </Form.Item>
            <Form.Item className="bottom">
              <Button type="primary" className="submit" htmlType="submit">
                确定
              </Button>
              <Button htmlType="button" onClick={handleCancel}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
      <Table
        rowKey="id"
        className="trademarkTable"
        columns={columns}
        dataSource={trademarkList}
        pagination={{
          // hideOnSinglePage: true, // 只有一页时不显示分页
          total: total, // 总共有多少条
          onChange: (page: number, pageSize: number) => {
            setCurrent(page);
            setPageSize(pageSize);
          }, // 页码变化回调函数
          pageSize: pageSize,
          showQuickJumper: true, // 是否显示快速跳转
          current: current, // 当前active的页码
          showSizeChanger: true, // 是否显示页面大小变化选择框
          pageSizeOptions: ["5", "10", "20"], // 页面大小变化选择框中可选变化
        }}
      />
    </Card>
  );
}

export default TrademarkPage;
